import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/request'
import { isURL } from '@/utils/validate'
import { userinfoList } from "./userinfo"

Vue.use(Router)
    // 页面路由(独立页面)
export const pageRoutes = [{
        path: '/404',
        component: () =>
            import ('@/views/pages/404'),
        name: '404',
        meta: { title: '404未找到' },
        beforeEnter(to, from, next) {
            // 拦截处理特殊业务场景
            // 如果, 重定向路由包含__双下划线, 为临时添加路由
            // if (/__.*/.test(to.redirectedFrom)) {
            //     return next(to.redirectedFrom.replace(/__.*/, ''))
            // }
            next()
        }
    },
    {
        path: '/',
        component: () =>
            import ('@/views/pages/login'),
        name: 'login',
        meta: { title: '登录' }
    }
]

// 模块路由(基于主入口布局页面)
export const moduleRoutes = {
    path: '/',
    component: () =>
        import ('@/views/main'),
    name: 'main',
    redirect: { name: 'home' },
    meta: { title: '主入口布局' },
    children: [{
        path: '/home',
        component: () =>
            import ('@/views/modules/home'),
        name: 'home',
        meta: { title: '首页', isTab: true }
    }]
}

export function addDynamicRoute(routeParams, router) {
    // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
    var routeName = routeParams.routeName
    var dynamicRoute = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
    if (dynamicRoute) {
        return router.push({ name: routeName, params: routeParams.params })
    }
    // 否则: 添加并全局变量保存, 再跳转
    dynamicRoute = {
        path: routeName,
        component: () =>
            import (`@/views/modules/${routeParams.path}`),
        name: routeName,
        meta: {
            ...window.SITE_CONFIG['contentTabDefault'],
            menuId: routeParams.menuId,
            title: `${routeParams.title}`
        }
    }
    router.addRoutes([{
        ...moduleRoutes,
        name: `main-dynamic__${dynamicRoute.name}`,
        children: [dynamicRoute]
    }])
    window.SITE_CONFIG['dynamicRoutes'].push(dynamicRoute)
    router.push({ name: dynamicRoute.name, params: routeParams.params })
}

const router = new Router({
        mode: 'hash',
        scrollBehavior: () => ({ y: 0 }),
        routes: pageRoutes.concat(moduleRoutes)
    })
    // 左侧菜单列表
    // console.log("执行")
router.beforeEach((to, from, next) => {
    // console.log(localStorage.getItem('token'))
    if (to.name !== "login") {
        // 如果token为空，则默认为login页面，无法通过地址输入跳转
        if (!localStorage.getItem('token')) {
            return next({ name: 'login' })
        }
    }
    return next()
})

/**
 * 判断当前路由是否为页面路由
 * @param {*} route 当前路由
 * @param {*} pageRoutes 页面路由
 */
function fnCurrentRouteIsPageRoute(route, pageRoutes = []) {
    var temp = []
        // console.log(pageRoutes)
    for (var i = 0; i < pageRoutes.length; i++) {
        if (route.path === pageRoutes[i].path) {
            return true
        }
        if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) {
            temp = temp.concat(pageRoutes[i].children)
        }
    }
    // console.log(temp);
    return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
export function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
    // console.log(routes)
    console.log(menuList)
        // console.log(menuList[3])
    var temp = []
    for (var i = 0; i < menuList.length; i++) {
        console.log(menuList[i])
        if (menuList[i].children && menuList[i].children.length >= 1) {
            temp = temp.concat(menuList[i].children)
            continue
        }
        // 组装路由
        var route = {
                path: '',
                component: null,
                name: '',
                meta: {
                    ...window.SITE_CONFIG['contentTabDefault'],
                    menuId: menuList[i].id,
                    title: menuList[i].name
                }
            }
            // eslint-disable-next-line
        let URL = (menuList[i].url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
        if (isURL(URL)) {
            route['path'] = route['name'] = `i-${menuList[i].id}`
            route['meta']['iframeURL'] = URL
        } else {
            URL = URL.replace(/^\//, '').replace(/_/g, '-')
            route['path'] = route['name'] = URL.replace(/\//g, '-')
            route['component'] = () =>
                import (`@/views/modules/${URL}`)
        }
        routes.push(route)
    }
    if (temp.length >= 1) {
        return fnAddDynamicMenuRoutes(temp, routes)
    }
    // 添加路由
    router.addRoutes([{
            ...moduleRoutes,
            name: 'main-dynamic-menu',
            children: routes
        },
        { path: '*', redirect: { name: '404' } }
    ])
    window.SITE_CONFIG['dynamicMenuRoutes'] = routes
    window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
}
userinfoList()
fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
export default router